package com.hoshiicloud.user.controller.usercenter;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.rpc.Response;
import com.hoshiicloud.user.controller.BaseController;
import com.hoshiicloud.user.entity.usercenter.MemberAddress;
import com.hoshiicloud.user.param.usercenter.MemberAddressPageParam;
import com.hoshiicloud.user.param.usercenter.MemberAddressUpdateParam;
import com.hoshiicloud.user.service.usercenter.IMemberAddressService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户收货地址Controller
 *
 * @author : yangcheng
 * @date : 2019/5/11 11:17
 * @mail : maiboyc@163.com
 **/
@RestController
@RequestMapping("/memberAddress")
@Api(value = "用户收货地址管理", tags = {"用户收货地址操作接口"}, produces = MediaType.APPLICATION_JSON_VALUE)
public class MemberAddressController extends BaseController {

    // 用户收货地址Service
    @Autowired
    private IMemberAddressService userAddressService;

    /**
     * 根据ID查询用户收货地址
     * @param id ID
     * @return Response
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "根据ID查询", notes = "根据ID查询用户收货地址", consumes = MediaType.ALL_VALUE)
    public Response<MemberAddress> getById(@PathVariable("id") Long id) {
        Response<MemberAddress> rs;
        try {
            rs = Response.data(userAddressService.getById(id));
        } catch (Exception e) {
            logger.error("根据ID查询用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID组查询用户收货地址
     * @param ids ID组
     * @return Response
     */
    @GetMapping("/getByIds")
    @ApiOperation(value = "根据ID组查询", notes = "根据ID组查询用户收货地址", consumes = MediaType.ALL_VALUE)
    public Response<List<MemberAddress>> getByIds(@RequestParam("ids") List<Long> ids) {
        Response<List<MemberAddress>> rs;
        try {
            rs = Response.data(userAddressService.getByIds(ids));
        } catch (Exception e) {
            logger.error("根据ID组查询用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据收件人姓名查询用户收货地址
     * @param name  收件人姓名
     * @return Response
     */
    @GetMapping("/find/{name}")
    @ApiOperation(value = "根据收件人姓名查询", notes = "根据收件人姓名查询用户收货地址", consumes = MediaType.ALL_VALUE)
    public Response<IPage<MemberAddress>> findByName(@PathVariable("name") String name) {
        Response<IPage<MemberAddress>> rs;
        try {
            MemberAddress entity = new MemberAddress();
            entity.setName(name);
            rs = Response.data(userAddressService.List(entity));
        } catch (Exception e) {
            logger.error("根据收件人姓名查询用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户收货地址（get请求，以具体值接收参数）
     * @param pageIndex     当前页码
     * @param pageSize      每页显示的记录数
     * @param name          收件人姓名
     * @param idCard        身份证
     * @param phone         手机
     * @param telephone     固话
     * @param postcode      邮编
     * @return Response
     */
    @GetMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户收货地址", consumes = MediaType.APPLICATION_JSON_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "当前页码", required = true, dataType = "Long", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示记录数", required = true, dataType = "Long", example = "10", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "收件人姓名", dataType = "String", example = "yangcheng", paramType = "query"),
            @ApiImplicitParam(name = "idCard", value = "身份证", dataType = "Integer",example = "42032419851214051C", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "Integer", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "telephone", value = "固话", dataType = "Integer", example = "1", paramType = "query"),
            @ApiImplicitParam(name = "postcode", value = "邮编", dataType = "Integer",example = "1",  paramType = "query")
    })
    public Response<IPage<MemberAddress>> list(Long pageIndex, Long pageSize, String name, String idCard, String phone, String telephone, String postcode) {
        Response<IPage<MemberAddress>> rs;
        try {
            MemberAddress entity = new MemberAddress();
            entity.setPageIndex(pageIndex);
            entity.setPageSize(pageSize);
            entity.setName(name);
            entity.setIdCard(idCard);
            entity.setPhone(phone);
            entity.setTelephone(telephone);
            entity.setPostcode(postcode);
            rs = Response.data(userAddressService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 分页查询用户收货地址（post请求，以对象接收参数）
     * @param param 查询参数实体
     * @return Response
     */
    @PostMapping("/list")
    @ApiOperation(value = "分页查询", notes = "分页查询用户收货地址", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<IPage<MemberAddress>> list(@RequestBody MemberAddressPageParam param) {
        Response<IPage<MemberAddress>> rs;
        try {
            MemberAddress entity = new MemberAddress();
            BeanUtils.copyProperties(param, entity);
            rs = Response.data(userAddressService.List(entity));
        } catch (Exception e) {
            logger.error("分页查询用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据参数查询用户收货地址
     * @param param 查询参数
     * @return Response<List<MemberAddress>>
     */
    @PostMapping("/getMemberAddresses")
    @ApiOperation(value = "根据参数查询", notes = "根据参数查询用户收货地址", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<List<MemberAddress>> getMemberAddresses(@RequestBody MemberAddress param) {
        Response<List<MemberAddress>> rs;
        try {
            rs = Response.data(userAddressService.getMemberAddresses(param));
        } catch (Exception e) {
            logger.error("分页查询用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 新增用户收货地址
     * @param entity 保存参数实体
     * @return Response
     */
    @PostMapping("/save")
    @ApiOperation(value = "新增用户收货地址", notes = "新增用户收货地址", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> save(@RequestBody @Valid MemberAddress entity, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                rs = Response.data(userAddressService.insert(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("新增用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        }catch (Exception e) {
            logger.error("新增用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 修改用户收货地址
     * @param param 修改参数实体
     * @return Response
     */
    @PutMapping("/update")
    @ApiOperation(value = "修改用户收货地址", notes = "修改用户收货地址", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Response<Long> updateById(@RequestBody @Valid MemberAddressUpdateParam param, BindingResult result) {
        Response<Long> rs;
        try {
            if (CollectionUtils.isNotEmpty(handleValidMsg(result))){// 验证不通过
                rs = Response.failed(objectMapper.writeValueAsString(handleValidMsg(result)));
            } else {// 验证通过
                MemberAddress entity = new MemberAddress();
                BeanUtils.copyProperties(param, entity);
                rs = Response.data(userAddressService.update(entity));
            }
        } catch (JsonProcessingException e) {
            logger.error("处理JSON验证信息异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        } catch (ServiceException e) {
            logger.error("更新用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("更新用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }

    /**
     * 根据ID删除用户收货地址
     * @param id 用户ID
     * @return Response
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除用户收货地址", consumes = MediaType.ALL_VALUE)
    public Response<Long> deleteById(@PathVariable("id") Long id) {
        Response<Long> rs;
        try {
            rs = Response.data(userAddressService.delete(id));
        } catch (ServiceException e) {
            logger.error("删除用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getError());
        } catch (Exception e) {
            logger.error("删除用户收货地址异常"+"["+e.getMessage()+"]");
            rs = Response.failed(e.getMessage());
        }
        return rs;
    }
    
}  